<!--
 * @Author: wjk
 * @Date: 2020-11-27 16:52:03
 * @LastEditors: wjk
 * @LastEditTime: 2020-12-25 15:54:09
 * @description: file content
-->
<template>
  <view class="article-item-container">
    <!-- 用户信息 -->
    <view v-if="fromType!=='user-center'" class="article-title">
      <view class="user-box" @click="toUserCenter">
        <view class="user-image">
          <b-image width="66" height="66" is-head :src="articleData.head_img_url || '/static/images/logo.png'" mode="aspectFill" />
        </view>
        <view class="user-name"> {{ articleData.nick_name }}</view>
      </view>
      <!-- 关注按钮 -->
      <view v-if="!articleData.oneself" class="attention-btn" @click="attentionOperator">
        <view v-if="attention_status === 1" class="attention-ned">已关注</view>
        <view v-if="attention_status === 2" class="attention-les">+关注</view>
        <view v-if="attention_status === 3" class="attention-ned">互相关注</view>
      </view>
    </view>
    <!-- 种草内容 -->
    <view class="article-content" @click="toDetail">
      <view id="articleContentHeight" class="article-content-height">
        <block v-if="contentList">
          <view v-for="(item, index) in contentList" :key="index" class="article-line">{{ item }}</view>
        </block>
        <view v-else class="content" v-text="articleData.content"></view>
      </view>
      <view v-if="contentHeight > 140" class="show-more">查看更多</view>
    </view>
    <view v-if="articleData.resource_object_list && articleData.resource_object_list.length > 0" class="article-resource" @click="toDetail">
      <!-- <view v-for="(item, index) in articleData.resource_object_list" :key="index" class="resourece-item">
        <b-image width="400" height="400" :src="item.resourceUrl" mode="aspectFill" />
      </view> -->
      <horizontalList ref="resource-list" list-name="resource" :list="articleData.resource_object_list" :other-params="{articleData: articleData}" emit-scroll-index @scrollIndexChange="scrollIndexChange">
        <template v-slot="{item, otherParams}">
          <view v-if="otherParams.articleData.type === 8" class="videoPos">
            <b-image width="750" height="400" :need-clip="false" :src="item.videoPreviewImg || otherParams.articleData.cover" mode="aspectFill" />
            <view class="videoPlay">
              <b-image width="100" height="100" is-asset src="/static/images/zb/icon_video_play.png" mode="aspectFill" />
            </view>
          </view>
          <view v-else @click="lookDetail(item.resourceUrl)">
            <b-image width="400" height="400" :need-clip="false" :src="item.resourceUrl" mode="aspectFill" />
          </view>
        </template>
      </horizontalList>
      <view v-if="articleData.resource_object_list && articleData.resource_object_list.length > 1" class="resource-nums">{{ (slideIndex || 1) }}/{{ articleData.resource_object_list && articleData.resource_object_list.length }}</view>
    </view>
    <view class="article-time">
      <view class="time-desc">{{ articleData.time_desc }}</view>
      <view class="article-zan">
        <view class="article-zan-button" @click="praiseOperator">
          <image v-if="is_praise" src="/static/images/icon/icon_zan_selected.png" mode="aspectFit" />
          <image v-else src="/static/images/icon/icon_zan_normal.png" mode="aspectFit" />
          {{ praise_num | formatNumber(2, true) }}
        </view>
        <view v-if="isMySelf" class="more">
          <image src="/static/images/icon/icon_more_list.png" mode="aspectFit" @click="showEdit = !showEdit" />
          <view v-if="showEdit" class="popup-box" :style="{'background-image': `url(${itemBg}/material/bg_material_edit.png)`}">
            <view class="text" @click="toEdit">编辑</view>
            <view class="text" @click="deleteItem">删除</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 商品跳转 -->
    <view v-if="goods && goods.goods_id" class="material-link" @click="toGoodsDetail">
      <view class="commodity-pic">
        <b-image width="60" height="60" :src="goods.goods_image_url" mode="aspectFit" />
      </view>
      <view class="commodity-title">{{ goods.goods_name }}</view>
      <view class="commodity-price">{{ goods.price | formatMoney }}</view>
    </view>
    <!-- 链接跳转 -->
    <view v-else-if="goods && goods.isUrl" class="material-link" @click="toUrl">
      <view class="commodity-pic">
        <b-image width="60" height="60" :src="goods.videoPreviewImg" mode="aspectFit" />
      </view>
      <view class="commodity-title" style="max-width: 600rpx">{{ goods.resourceText }}</view>
    </view>
    <!-- 底部按钮控制 -->
    <view class="article-control-box">
      <template v-if="articleData.status===4">
        <view class="btn-flex" @click="copy">
          <image src="/static/images/icon/icon_material_copy.png" mode="aspectFit" />复制
        </view>
        <!-- #ifndef H5 -->
        <view class="btn-flex" @click="download">
          <image src="/static/images/icon/icon_material_download.png" mode="aspectFit" />下载
        </view>
        <!-- #endif -->
        <view class="btn-flex" @click="showShare">
          <image src="/static/images/icon/icon_material_share.png" mode="aspectFit" />分享
        </view>
      </template>
      <view v-if="articleData.status===2" class="btn-flex" @click="toEdit">待审核</view>
      <view v-if="articleData.status===8" class="btn-flex" @click="toEdit">审核不通过</view>
    </view>
    <share v-if="showShareDia" ref="drawImage" :share-types="[3,5]" :share-option="shareOption" />
    <confirm-popup ref="confirm" />
  </view>
</template>
<script>
import { mapState } from 'vuex'
import confirmPopup from '@/components/confirmPopup/index'
import horizontalList from '@/components/horizontalList/index'
import share from '@/components/draw/share'
import { toGoods, h5NavigateTo } from '@/utils/navigateTo'
import { setClipboardData } from '@/utils/tools'
export default {
  components: {
    horizontalList,
    confirmPopup,
    share
  },
  props: {
    className: { type: String, default: '' }, // 自定义样式类名
    isMySelf: { type: Boolean, default: false }, // 是否是自己的种草
    fromType: {
      type: String,
      default: ''
    },
    articleData: {
      type: Object,
      default() {
        return {
          attention_status: false, // 是否关注 1:已关注 2：未关注 3：相互关注
          browse_num: 0, // 浏览次数
          download_num: 0, // 下载次数
          material_link_object: {
            content: '',
            fromType: '',
            goodsType: '',
            goodsUrl: '',
            marketPrice: '',
            packType: '',
            picUrl: '',
            price: '',
            targetValue: '' // 如果跳转为链接则为url，如为内页则存储活动id或者商品id
          }, // 素材链接信息
          resource_object_list: '',
          media_type: 0, // 素材媒体类型
          title: '', // 名称
          content: '', // 内容
          type: '', // 素材类型：2 - 单图,4 - 多图,8 - 视频, 10 - 文章，12 - 产品
          url_detail: '', // 跳转明细
          url_type: '', // 跳转类型
          time_desc: '', // 时间显示： 0-60s显示 刚刚发布 1-60分钟 显示1分钟前 1-24小时 显示1小时前 1-30天显示 1天前 超过30天显示 2020-10-10
          head_img_url: '', // 用户头像
          status: '' // 审核状态 未审核：2 审核通过：4 审核未通过：8
        }
      }
    }
  },
  data() {
    return {
      attention_status: 0,
      is_praise: false,
      praise_num: 0,
      slideIndex: 1,
      shareOption: {},
      showShareDia: false,
      showEdit: false,
      goods: {}, // 商品素材之商品信息
      itemBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/`,
      contentHeight: 20
    }
  },
  computed: {
    contentList() {
      if (!this.articleData.content) return ''
      return this.articleData.content.split('\n')
    },
    ...mapState([
      'token',
      'userInfo'
    ])
  },
  watch: {
    articleData() {
      this.init()
    }
  },
  created() {
  },
  mounted() {
    this.$nextTick(function() {
      this.init()
    })
  },
  methods: {
    init() {
      this.goods = this.articleData.goods.length ? this.articleData.goods[0] : {}
      if (this.articleData.url_detail && !this.goods.goods_id) {
        try {
          const temp = JSON.parse(this.articleData.url_detail)
          if (temp.resourceUrl && temp.resourceText) {
            this.goods = { ...temp, isUrl: true }
          }
          //  else if (temp.goodsUrl && temp.picUrl) {
          //   this.goods = {
          //     id: temp.targetValue,
          //     goods_id: temp.targetValue,
          //     market_price: temp.marketPrice,
          //     goods_name: temp.content,
          //     from_type: temp.fromType,
          //     price: temp.price,
          //     goods_type: temp.goods_type,
          //     pack_type: temp.packType,
          //     goods_image_url: temp.picUrl
          //   }
          // }
        } catch (error) {
          console.log('error', error)
        }
      }
      this.attention_status = this.articleData.attention_status
      this.is_praise = this.articleData.is_praise
      this.praise_num = this.articleData.praise_num
      // this.articleData.contentList = this.articleData.content.split('\n')
      setTimeout(() => {
        uni.createSelectorQuery().in(this).select('#articleContentHeight').boundingClientRect(data => {
          if (!data) return
          this.contentHeight = data.height
        }).exec()
      }, 200)
    },
    async attentionOperator() {
      if (!this.token) {
        this.$navigateTo('/pages/login/index')
        return
      }
      const operatorType = this.attention_status === 2 ? 1 : 0
      const res = await this.$api.materialApi.attentionOperator({
        operatorType,
        userId: this.articleData.user_id
      })
      if (res.success) {
        // this.articleData.attention_status = res.data.attentionStatus
        this.$set(this, 'attention_status', res.data.attentionStatus)
        this.$emit('handleEvent', {
          attention_status: res.data.attentionStatus,
          user_id: this.articleData.user_id
        })
        uni.showToast({
          title: this.attention_status === 2 ? '取消关注成功' : '关注成功',
          icon: 'none',
          duration: 2000
        })
      }
    },
    async praiseOperator() {
      if (!this.token) {
        this.$navigateTo('/pages/login/index')
        return
      }
      const praise = this.is_praise ? 0 : 1
      const res = await this.$api.materialApi.praiseOperator({
        praise,
        currentUserId: this.userInfo ? this.userInfo.uid : '',
        id: this.articleData.id,
        praiseNum: this.praise_num,
        userId: this.articleData.user_id,
        zhongCaoUserId: this.articleData.zhong_cao_user_id
      })
      if (res.success) {
        // this.articleData.is_praise = res.data.isPraise
        // this.articleData.praise_num = res.data.praiseNum
        this.$set(this, 'is_praise', res.data.isPraise)
        this.$set(this, 'praise_num', res.data.praiseNum)
        uni.showToast({
          title: res.data.isPraise ? '点赞成功' : '点赞已取消',
          icon: 'none',
          duration: 2000
        })
      }
    },
    async operaCount(countType) {
      // 操作类型：1 ~ 分享统计，2 ~ 下载统计，3 ~ 浏览统计，4 ~ 复制统计,5 ~ 点赞统计
      const res = await this.$api.materialApi.materialCount({
        countType,
        id: this.articleData.id
      })
      if (res.success) {
        console.log('res', res)
      }
    },
    setAttention(e) {
      this.attention_status = e
    },
    toUserCenter() {
      this.$navigateTo(`/pagesMaterial/user-center/index?materialUserId=${this.articleData.user_id}`)
    },
    async deleteItem() {
      this.showEdit = false
      this.$refs.confirm.show({
        title: '温馨提示',
        yesTxt: '确认删除',
        content: '删除后无法恢复哦，确定删除吗？',
        yesCb: async() => {
          const res = await this.$api.materialApi.materialDelete({
            id: this.articleData.id
          })
          if (res.success) {
            this.$emit('refresh')
            uni.showToast({
              title: '删除成功',
              icon: 'none',
              duration: 2000
            })
          }
        },
        cancleCb: async() => {
        }
      })
    },
    // 复制链接
    copy() {
      this.$emit('btnClick', '复制')
      if (this.articleData.content) {
        setClipboardData({
          data: this.articleData.content,
          success: () => {
            uni.showToast({
              title: '文案复制成功',
              icon: 'none',
              duration: 1500
            })
            this.operaCount(4)
          }
        })
        return
      }
    },
    async download() {
      this.$downloadFile(this.articleData.resource_object_list, {
        fileType: this.articleData.type === 8 ? 'Video' : 'Image',
        fileKey: 'resourceUrl',
        callback: (successNum, failNum) => {
          if (successNum > 0) {
            uni.showToast({ title: '已保存到本地相册', icon: 'none' })
          }
        }
      })
      this.operaCount(2)
    },
    scrollIndexChange(index) {
      this.slideIndex = index + 1
    },
    showShare() {
      if (!this.token) {
        this.$navigateTo('/pages/login/index')
        return
      }
      let url = `${process.env.VUE_APP_PRE_URL}/pagesMaterial/detail/index?id=` + this.articleData.id
      const share_route = `/pagesMaterial/detail/index?id=` + this.articleData.id
      // #ifndef H5
      url = share_route
      // #endif
      this.shareOption = {
        share_title: this.articleData.title,
        share_url: url,
        share_route,
        share_icon: this.articleData.cover || '',
        share_image: this.articleData.cover || '',
        share_list: [
          {
            pic: this.articleData.cover,
            titleArr: [
              this.articleData.title
            ]
          }
        ]
      }
      if (this.articleData.resource_object_list && this.articleData.resource_object_list.length && this.articleData.type !== 8) {
        this.shareOption.share_list = this.articleData.resource_object_list.map(item => {
          return {
            pic: item.resourceUrl,
            titleArr: [
              this.articleData.title
            ]
          }
        })
      }
      this.showShareDia = true
      this.$emit('initShare', this.shareOption)
      this.$nextTick(() => {
        this.$refs.drawImage.show(this.shareOption)
        this.operaCount(1)
      })
    },
    toGoodsDetail() {
      if (this.goods && this.goods.goods_id) {
        toGoods(this.goods)
      }
    },
    toDetail() {
      if (this.articleData.status !== 4) {
        this.toEdit()
      } else {
        this.$navigateTo(`/pagesMaterial/detail/index?id=${this.articleData.id}&fromType=${this.fromType}`)
      }
    },
    toEdit() {
      this.showEdit = false
      this.$navigateTo('/pagesMaterial/publish/index?id=' + this.articleData.id)
    },
    toUrl() {
      h5NavigateTo(this.goods.resourceUrl)
    },
    lookDetail(item) {
      // const urls = this.articleData.resource_object_list.map(i => i.resourceUrl)
      // uni.previewImage({
      //   current: item,
      //   urls: urls
      // })
    }
  }
}
</script>
<style lang="scss">
.article-item-container{
  display: flex;
  padding: 30rpx 20rpx;
  box-sizing: border-box;
  flex-direction: column;
  background-color: #fff;
  .article-title{
    display: flex;
    align-items: center;
    // padding-left: 20rpx;
    margin-bottom: 20rpx;
    justify-content: space-between;
    .user-box{
      display: flex;
      align-items: center;
      .user-image{
        width: 66rpx;
        border-radius: 50%;
        overflow: hidden;
        height: 66rpx;
        image{
          border-radius: 50%;
        }
      }
      .user-name{
        margin-left: 24rpx;
        font-size: 28rpx;
        color: #000;
      }
    }
    .attention-btn{
      width: 140rpx;
      height: 54rpx;
      line-height: 54rpx;
      text-align: center;
      font-size: 26rpx;
      .attention-ned{
        border-radius: 2px;
        border: 2rpx solid #ccc;
        color: #ccc;
      }
      .attention-les{
        border-radius: 2px;
        border: 2rpx solid #000;
        color: #000;
      }
    }
  }
  .article-content{
    line-height: 20px;
    font-size: 28rpx;
    .article-content-height{
      max-height: 141px;
      overflow: hidden;
    }
    .article-line{
      display: block;
      line-height: 20px;
      min-height: 20px;
    }
    .content{
      font-size: 28rpx;
      line-height: 20px;
    }
    .show-more{
      margin: 10rpx 0 10rpx 0;
      color: #999;
    }
  }
  .resource-list{
    height: 400rpx;
    position: relative;
    .resource-item{
      @include flex(column, inline-flex);
      @include center;
      margin-right: 10rpx;
      .videoPos{
        position: relative;
        .videoPlay{
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translateX(-50%) translateY(-50%);
        }
      }
    }
  }
  .article-resource{
    position: relative;
    margin: 10rpx 0;
    .resource-nums{
      position: absolute;
      bottom: 20rpx;
      right: 20rpx;
      background: rgba(0,0,0,0.5);
      color: white;
      font-size: 22rpx;
      height: 30rpx;
      padding: 0 10rpx;
      line-height: 30rpx;
      border-radius: 15rpx;
    }
  }
  .article-time{
    display: flex;
    align-items: center;
    margin: 10rpx 0;
    justify-content: space-between;
    .time-desc{
      color: #999;
      font-size: 20rpx;
    }
    .article-zan{
      display: flex;
      align-items: center;
      image{
        width: 30rpx;
        height: 30rpx;
        margin-right: 15rpx;
      }
      .article-zan-button{
        display: flex;
        align-items: center;
      }
    }
    .more{
        position: relative;
        display: flex;
        align-items: center;
        margin-left: 26rpx;
        image{
          // margin-bottom: -8rpx;
          width: 36rpx;
          height: 36rpx;
        }
        .popup-box{
          z-index: 1;
          position: absolute;
          width: 220rpx;
          height: 194rpx;
          background-size: 100% 100%;
          box-sizing: border-box;
          right: -10rpx;
          padding: 20rpx 0;
          top: 30rpx;
          .text{
            width: 145rpx;
            height: 76rpx;
            box-sizing: border-box;
            text-align: center;
            border-bottom: 1px solid $color-border;
            margin: 0 37rpx;
            // padding-top: 20rpx;
            line-height: 76rpx;
            &:nth-last-child(1) {
              border-bottom: none;
            }
          }
        }
      }
  }
  .material-link{
    display: flex;
    width: 710rpx;
    height: 90rpx;
    margin: 20rpx 0rpx;
    padding: 15rpx;
    align-items: center;
    position: relative;
    background-color: #f5f5f5;
    box-sizing: border-box;
    .commodity-pic{
      width: 60rpx;
      height: 60rpx;
      margin-right: 15rpx;
    }
    .commodity-title{
      @include text-ellipsis-line(1);
      font-size: 26rpx;
      max-width: 430rpx;
    }
    .commodity-price{
      position: absolute;
      right: 15rpx;
      line-height: 90rpx;
      color: #000;
      font-weight: bold;
      font-size: 28rpx;
      &::before{
        font-size: 20rpx;
        content: '￥';
      }
    }
  }
  .article-control-box{
    margin-top: 10rpx;
    display: flex;
    padding: 0 8rpx;
    align-items: center;
    .btn-flex{
      flex: 1;
      image{
        width: 30rpx;
        height: 30rpx;
        margin-right: 20rpx;
      }
      display: flex;
      align-items: center;
      justify-content: center;

    }
  }
}
</style>
